from flask import Blueprint, request, jsonify, send_file, current_app, abort
from flask_jwt_extended import jwt_required, get_jwt
import os
from urllib.parse import unquote
from controllers.admin_controller import AdminController
from utils.admin_required import admin_required

admin_bp = Blueprint('admin', __name__)

# 1. 认证相关接口
@admin_bp.route('/login', methods=['POST'])
def admin_login():
    data = request.get_json()
    result = AdminController.admin_login(data)
    return jsonify(result)

# 2. 用户管理接口
@admin_bp.route('/users', methods=['GET'])
@jwt_required()
@admin_required
def get_users():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    search = request.args.get('search', '')
    result = AdminController.get_users(page, limit, search)
    return jsonify(result)

@admin_bp.route('/users', methods=['POST'])
@jwt_required()
@admin_required
def add_user():
    data = request.get_json()
    result = AdminController.add_user(data)
    return jsonify(result)

@admin_bp.route('/users/<int:user_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_user(user_id):
    data = request.get_json()
    result = AdminController.update_user(user_id, data)
    return jsonify(result)

@admin_bp.route('/users/<int:user_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_user(user_id):
    result = AdminController.delete_user(user_id)
    return jsonify(result)

# 3. 句子管理接口
@admin_bp.route('/sentences', methods=['GET'])
@jwt_required()
@admin_required
def get_sentences():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    search = request.args.get('search', '')
    result = AdminController.get_sentences(page, limit, search)
    return jsonify(result)

@admin_bp.route('/sentences', methods=['POST'])
@jwt_required()
@admin_required
def add_sentence():
    data = request.get_json()
    result = AdminController.add_sentence(data)
    return jsonify(result)

@admin_bp.route('/sentences/batch-import', methods=['POST'])
@jwt_required()
@admin_required
def batch_import_sentences():
    if 'file' not in request.files:
        return jsonify({'code': 400, 'message': '没有文件', 'data': None})
    
    file = request.files['file']
    result = AdminController.batch_import_sentences(file)
    return jsonify(result)

@admin_bp.route('/sentences/<int:sentence_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_sentence(sentence_id):
    data = request.get_json()
    result = AdminController.update_sentence(sentence_id, data)
    return jsonify(result)

@admin_bp.route('/sentences/<int:sentence_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_sentence(sentence_id):
    result = AdminController.delete_sentence(sentence_id)
    return jsonify(result)

# 4. 录音管理接口
@admin_bp.route('/recordings', methods=['GET'])
@jwt_required()
@admin_required
def get_recordings():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    username = request.args.get('username', '')
    sentence_content = request.args.get('sentence_content', '')
    result = AdminController.get_recordings(page, limit, username, sentence_content)
    return jsonify(result)

@admin_bp.route('/recordings/<int:recording_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_recording(recording_id):
    # Get recording data first to verify it exists
    result = AdminController.get_recording(recording_id)
    
    # If recording doesn't exist, return error JSON
    if result['code'] != 200:
        return jsonify(result)
    
    # Get the file path from the recording data
    audio_file_path = result['data']['audio_file']
    
    # Extract filename from the path
    filename = os.path.basename(audio_file_path)
    
    # Build the full file system path
    file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
    
    # Check if file exists
    if not os.path.exists(file_path):
        return jsonify({
            'code': 404, 
            'message': '音频文件不存在', 
            'data': None
        })
    
    # 读取音频文件内容并转换为base64编码
    import base64
    with open(file_path, 'rb') as audio_file:
        audio_data = audio_file.read()
        audio_base64 = base64.b64encode(audio_data).decode('utf-8')
    
    # 更新返回结果，包含完整的data URL格式的音频内容而不是路径
    result['data']['audio_content'] = f"data:audio/wav;base64,{audio_base64}"
    result['data']['audio_type'] = "audio/wav"
    del result['data']['audio_file']  # 删除原来的文件路径字段
    
    return jsonify(result)

@admin_bp.route('/recordings/<int:recording_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_recording(recording_id):
    result = AdminController.delete_recording(recording_id)
    return jsonify(result)

@admin_bp.route('/recordings/download/<int:recording_id>', methods=['GET'])
@jwt_required()
@admin_required
def download_recording(recording_id):
    file_path = AdminController.download_recording(recording_id)
    
    if not file_path:
        return jsonify({'code': 404, 'message': '文件不存在', 'data': None})
    
    return send_file(file_path, mimetype='audio/wav', as_attachment=True)

@admin_bp.route('/recordings/export/user/<int:user_id>', methods=['GET'])
@jwt_required()
@admin_required
def export_user_recordings(user_id):
    memory_file = AdminController.export_user_recordings(user_id)
    
    if not memory_file:
        return jsonify({'code': 404, 'message': '没有找到录音文件', 'data': None})
    
    return send_file(
        memory_file,
        mimetype='application/zip',
        as_attachment=True,
        download_name=f'user_{user_id}_recordings.zip'
    )

@admin_bp.route('/recordings/export/sentence/<int:sentence_id>', methods=['GET'])
@jwt_required()
@admin_required
def export_sentence_recordings(sentence_id):
    memory_file = AdminController.export_sentence_recordings(sentence_id)
    
    if not memory_file:
        return jsonify({'code': 404, 'message': '没有找到录音文件', 'data': None})
    
    return send_file(
        memory_file,
        mimetype='application/zip',
        as_attachment=True,
        download_name=f'sentence_{sentence_id}_recordings.zip'
    )

@admin_bp.route('/recordings/export/all', methods=['GET'])
@jwt_required()
@admin_required
def export_all_recordings():
    memory_file = AdminController.export_all_recordings()
    
    if not memory_file:
        return jsonify({'code': 404, 'message': '没有找到录音文件', 'data': None})
    
    return send_file(
        memory_file,
        mimetype='application/zip',
        as_attachment=True,
        download_name='all_recordings.zip'
    )

# 新增接口：获取用户录音数量
@admin_bp.route('/recordings/count/user/<int:user_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_user_recordings_count(user_id):
    result = AdminController.get_user_recordings_count(user_id)
    return jsonify(result)

# 新增接口：获取句子录音数量
@admin_bp.route('/recordings/count/sentence/<int:sentence_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_sentence_recordings_count(sentence_id):
    result = AdminController.get_sentence_recordings_count(sentence_id)
    return jsonify(result)

# 新增接口：通过文件路径直接访问音频文件
@admin_bp.route('/recordings/file/<path:file_path>', methods=['GET'])
@jwt_required()
@admin_required
def get_audio_file_by_path(file_path):
    try:
        # 解码文件路径
        decoded_path = unquote(file_path)
        
        # 安全检查：确保只能访问录音文件夹下的文件
        if '..' in decoded_path or not decoded_path.startswith('storage/recordings/'):
            return jsonify({'code': 403, 'message': '访问被拒绝', 'data': None}), 403
        
        # 构建完整的文件路径
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        full_path = os.path.join(base_dir, decoded_path)
        
        # 检查文件是否存在
        if not os.path.exists(full_path) or not os.path.isfile(full_path):
            return jsonify({'code': 404, 'message': '文件不存在', 'data': None}), 404
        
        # 返回文件
        return send_file(full_path, mimetype='audio/wav')
    
    except Exception as e:
        # 记录错误
        print(f"Error accessing file: {e}")
        return jsonify({'code': 500, 'message': f'服务器错误: {str(e)}', 'data': None}), 500

# 5. 系统统计接口
@admin_bp.route('/stats', methods=['GET'])
@jwt_required()
@admin_required
def get_stats():
    result = AdminController.get_stats()
    return jsonify(result)

@admin_bp.route('/recordings/latest', methods=['GET'])
@jwt_required()
@admin_required
def get_latest_recordings():
    limit = request.args.get('limit', 5, type=int)
    result = AdminController.get_latest_recordings(limit)
    return jsonify(result)

# ==================== 句子分配管理接口 ====================

@admin_bp.route('/assignments/user/<int:user_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_user_assignments(user_id):
    """获取用户的句子分配情况"""
    result = AdminController.get_user_assignments(user_id)
    return jsonify(result)

@admin_bp.route('/assignments/assign', methods=['POST'])
@jwt_required()
@admin_required
def assign_sentences():
    """给用户分配句子"""
    data = request.get_json()
    user_id = data.get('user_id')
    sentence_ids = data.get('sentence_ids')
    replace_existing = data.get('replace_existing', True)

    if not user_id or not sentence_ids:
        return jsonify({'code': 400, 'message': '缺少必要参数', 'data': None}), 400

    result = AdminController.assign_sentences_to_user(user_id, sentence_ids, replace_existing)
    return jsonify(result)

@admin_bp.route('/assignments/assign-random', methods=['POST'])
@jwt_required()
@admin_required
def assign_random_sentences():
    """随机分配句子给用户"""
    data = request.get_json()
    user_id = data.get('user_id')
    count = data.get('count', 5)
    exclude_completed = data.get('exclude_completed', True)

    if not user_id:
        return jsonify({'code': 400, 'message': '缺少用户ID', 'data': None}), 400

    result = AdminController.assign_random_sentences(user_id, count, exclude_completed)
    return jsonify(result)

@admin_bp.route('/assignments/batch-assign', methods=['POST'])
@jwt_required()
@admin_required
def batch_assign_sentences():
    """批量分配句子给多个用户"""
    data = request.get_json()
    user_ids = data.get('user_ids')
    sentence_ids = data.get('sentence_ids')
    assignment_type = data.get('assignment_type', 'fixed')  # fixed | random
    count = data.get('count', 5)

    if not user_ids:
        return jsonify({'code': 400, 'message': '缺少用户ID列表', 'data': None}), 400

    result = AdminController.batch_assign_sentences(user_ids, sentence_ids, assignment_type, count)
    return jsonify(result)

@admin_bp.route('/assignments/overview', methods=['GET'])
@jwt_required()
@admin_required
def get_assignment_overview():
    """获取所有用户的分配概览"""
    result = AdminController.get_assignment_overview()
    return jsonify(result)

@admin_bp.route('/assignments/sentence-stats', methods=['GET'])
@jwt_required()
@admin_required
def get_sentence_usage_stats():
    """获取句子使用统计"""
    result = AdminController.get_sentence_usage_stats()
    return jsonify(result)

@admin_bp.route('/assignments/clear/<int:user_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def clear_user_assignments(user_id):
    """清空用户的所有分配"""
    result = AdminController.clear_user_assignments(user_id)
    return jsonify(result)

# ==================== 分配模板管理接口 ====================

@admin_bp.route('/templates', methods=['GET'])
@jwt_required()
@admin_required
def get_assignment_templates():
    """获取所有分配模板"""
    result = AdminController.get_assignment_templates()
    return jsonify(result)

@admin_bp.route('/templates', methods=['POST'])
@jwt_required()
@admin_required
def create_assignment_template():
    """创建分配模板"""
    data = request.get_json()
    name = data.get('name')
    description = data.get('description')
    sentence_ids = data.get('sentence_ids')
    category = data.get('category')

    if not name or not sentence_ids:
        return jsonify({'code': 400, 'message': '缺少必要参数', 'data': None}), 400

    result = AdminController.create_assignment_template(name, description, sentence_ids, category)
    return jsonify(result)

@admin_bp.route('/templates/<int:template_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_assignment_template(template_id):
    """删除分配模板"""
    result = AdminController.delete_assignment_template(template_id)
    return jsonify(result)

@admin_bp.route('/templates/<int:template_id>/apply', methods=['POST'])
@jwt_required()
@admin_required
def apply_template_to_users(template_id):
    """将模板应用到用户"""
    data = request.get_json()
    user_ids = data.get('user_ids')

    if not user_ids:
        return jsonify({'code': 400, 'message': '缺少用户ID列表', 'data': None}), 400

    result = AdminController.apply_template_to_users(template_id, user_ids)
    return jsonify(result)